using System;
using System.Collections;
using System.Text;

namespace Glpt.Common
{
    /// <summary>
    /// URL参数类
    /// </summary>
    public class UrlParams
    {
        private Hashtable hst = new Hashtable();
        private const string SepChar = "|`|";
        private string str_url = "";
        /// <summary>
        /// URL
        /// </summary>
        public string URL
        {
            get
            {
                return str_url;
            }
            set
            {
                string url = value;
                int idx1 = url.IndexOf("FORWARD_PARAMS=");
                if (idx1 > 0)
                {
                    string pas = "";
                    str_url = url.Substring(0, idx1);
                    idx1 += "FORWARD_PARAMS=".Length;
                    int idx2 = url.IndexOf("&", idx1);
                    if (idx2 > 0)
                    {
                        pas = url.Substring(idx1, idx2 - idx1);
                        if (str_url.EndsWith("&") || str_url.EndsWith("?"))
                            str_url += url.Substring(idx2 + 1);
                        else
                            str_url += url.Substring(idx2);
                    }
                    else
                        pas = url.Substring(idx1);
                    if (str_url.EndsWith("&") || str_url.EndsWith("?"))
                        str_url = str_url.Substring(0, str_url.Length - 1);
                    Init(pas);
                }
                else
                    str_url = value;
            }
        }

        /// <summary>
        /// 初始化类的新实例
        /// </summary>
        public UrlParams()
        {
        }

        /// <summary>
        /// 初始化类的新实例
        /// </summary>
        /// <param name="value">参数值</param>
        public UrlParams(string value)
        {
            Init(value);
        }

        private void Init(string value)
        {
            bool isok = false;
            try
            {
                if (value != null && value.Length > 0)
                {
                    string[] vals = GetStringFromBase64(value).Split(new string[] { SepChar }, StringSplitOptions.None);
                    for (int i = 0; i < vals.Length - 1; i = i + 2)
                    {
                        if (vals[i].ToUpper().Equals("TIME"))
                        {
                            DateTime dt = Funcs.StrToDataTime(vals[i + 1]);
                            if (Math.Abs(DateTime.Now.Ticks - dt.Ticks) / 10000000 <= 3600 * 24)
                                isok = true;
                        }
                        if (!vals[i].Equals("TIME"))
                            hst.Add(vals[i], vals[i + 1]);
                    }
                }
                else
                    isok = true;
            }
            catch { }
            if (!isok)
                throw new Exception("时间戳超时");
        }

        /// <summary>
        /// 参数个数
        /// </summary>
        /// <returns></returns>
        public int Count
        {
            get
            {
                return hst.Count;
            }
        }

        /// <summary>
        /// 添加参数
        /// </summary>
        /// <param name="name">参数名</param>
        /// <param name="value">参数值</param>
        public void Add(string name, string value)
        {
            if (hst.ContainsKey(name))
                hst.Remove(name);
            hst.Add(name, value);
        }

        /// <summary>
        /// 获取参数值
        /// </summary>
        /// <param name="name">参数名称</param>
        /// <returns>参数值</returns>
        public string GetValue(string name)
        {
            if (hst.Contains(name))
                return hst[name].ToString();
            else
                return null;
        }

        /// <summary>
        /// 参数名称列表
        /// </summary>
        public string[] KeyNames
        {
            get
            {
                string[] values = new string[hst.Count];
                int i = 0;
                foreach (DictionaryEntry de in hst)
                {
                    values[i++] = de.Key.ToString();
                }
                return values;
            }
        }

        /// <summary>
        /// 生成字符串
        /// </summary>
        /// <returns>字符串</returns>
        public string ToString(DateTime dt)
        {
            string sval = "";
            if (hst.Count > 0)
            {
                sval = "TIME" + SepChar + dt.ToString("yyyyMMddHHmmss");
                foreach (DictionaryEntry de in hst)
                {
                    sval += SepChar + de.Key + SepChar + de.Value;
                }
                sval = ToBase64String(sval);
            }
            string url = URL;
            if (url.Length > 0 && sval.Length > 0)
            {
                if (url.IndexOf("?") < 0) url += "?";
                if (!url.EndsWith("?") && !url.EndsWith("&")) url += "&";
                url += "FORWARD_PARAMS=" + sval;
            }
            return url;
        }

        /// <summary>
        /// 把Base64转成文本信息
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>字符串</returns>
        public static string GetStringFromBase64(string str)
        {
            string ret = "";
            if (str != null && str.Length > 0)
                ret = Encoding.UTF8.GetString(Convert.FromBase64String(str.Replace("%2B", "+")));
            return ret;
        }

        /// <summary>
        /// 把文本信息转成Base64
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>字符串</returns>
        public static string ToBase64String(string str)
        {
            string ret = "";
            if (str != null && str.Length > 0)
                ret = Convert.ToBase64String(Encoding.UTF8.GetBytes(str)).Replace("+", "%2B");
            return ret;
        }

        /// <summary>
        /// 读取文件,返回DataSet对象
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>数据集</returns>
        public static System.Data.DataSet ReadDataSetFromBase64(String str)
        {
            System.Data.DataSet dset = new System.Data.DataSet();
            if (str != null && str.Length > 0)
            {
                str = GetStringFromBase64(str);
                int ibegin = 0;
                int iend = str.IndexOf("<?xml ");
                while (iend >= 0)
                {
                    byte[] buf = null;
                    iend = str.IndexOf("<?xml ", ibegin + 1);
                    if (iend < 0)
                    {
                        buf = Encoding.UTF8.GetBytes(str.Substring(ibegin));
                    }
                    else
                    {
                        buf = Encoding.UTF8.GetBytes(str.Substring(ibegin, iend - ibegin));
                        ibegin = iend;
                    }
                    using (System.IO.MemoryStream fs = new System.IO.MemoryStream())
                    {
                        fs.Write(buf, 0, buf.Length);
                        fs.Position = 0;
                        System.Data.DataSet ds = new System.Data.DataSet();
                        ds.ReadXml(fs);
                        fs.Close();
                        dset.Merge(ds);
                    }
                }
            }
            return dset;
        }
    }
}
